package algo;

import android.handler.Handler;
import android.handler.Looper;
import android.handler.Message;
import org.apache.log4j.Logger;

import java.util.concurrent.CountDownLatch;

/**
 * @author Ajie
 * @date 8/8/24
 * @function
 */
public class CommonHandler {
    private static final Logger logger = Logger.getLogger(CommonHandler.class);
    
    private static final String TAG = "CommonHandler";

    public static final int GgsensorData = 10;
    public static final int DistanceMathInit = 11;
    public static final int DistanceMath = 12;
    public static final int DistanceMathLastTime = 13;

    private Handler handler;
    private static CountDownLatch latch = new CountDownLatch(1);
    private CommonHandler() {
        Thread initThread = new Thread(new Runnable() {
            @Override
            public void run() {
                logger.info("CommonHandler: looper will prepare in thisThread");
                Looper.prepare();
                handler = new Handler() {
                    @Override
                    public void handlerMessage(Message msg) {
                        super.handlerMessage(msg);
//                        logger.info("handlerMessage what:" + msg.what + " " + msg.obj);
                        switch (msg.what) {
                            case DistanceMathInit:
                                DistanceAlgoManager.getInstance().onInit();
                                break;
                            case DistanceMath:
                                DistanceAlgoManager.getInstance().onMathDistance();
                                break;
                            case DistanceMathLastTime:
                                DistanceAlgoManager.getInstance().onMathDistanceLastTime();
                                break;

                        }
                    }
                };
                logger.info("run: will countDown");
                latch.countDown(); // 减少计数，表示线程初始化完成
                // 启动Looper循环获取消息
                Looper.loop();
            }
        }, "My-CommonHandlerThread");
        initThread.start();
    }
    private static class SingletonInstance {
        private static final CommonHandler INSTANCE = new CommonHandler();
    }
    public static CommonHandler getInstance() {
        CommonHandler instance = SingletonInstance.INSTANCE;
        try {
            latch.await(); // 等待线程初始化完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Initialization interrupted", e);
        }
        return instance;
    }
    public Handler getHandler(){return handler;}

}
